#include "weatherTool.h"

QMap<QString, QString> WeatherTool::name_codeMap = {};
void WeatherTool::initMap()
{
    QString filePath = ":/res/citycode.json";
    QFile file(filePath);
    file.open(QIODevice::ReadOnly | QIODevice::Text);
    QByteArray json = file.readAll();
    file.close();
    QJsonParseError err;
    QJsonDocument doc = QJsonDocument::fromJson(json, &err);
    if (err.error != QJsonParseError::NoError) {
       return;
    }
    if (!doc.isArray()) {
        return;
    }
    QJsonArray cities = doc.array();
    for (int i = 0; i<cities.size(); i++) {
        QString city = cities[i].toObject().value("city_name").toString();
        QString code = cities[i].toObject().value("city_code").toString();
        if (code.size()>0) {
            name_codeMap.insert(city, code);
        }
    }
}

QString WeatherTool::getCityCode(QString cityName)
{

    if (name_codeMap.isEmpty()) {
       initMap();
    }
    if (name_codeMap.count(cityName))return name_codeMap.value(cityName);
    else {
        QString suffix[] = { "市","区","县","镇","乡","村","街道" };
        for (auto& s : suffix) {
            if(name_codeMap.count(cityName + s))return name_codeMap.value(cityName + s);
        }
    }
    
    // QMap<QString, QString>::iterator it = name_codeMap.find(cityName);
    // if (it == name_codeMap.end()) {
    //     it = name_codeMap.find(cityName + "市");
    // }
    // if (it != name_codeMap.end()) {
    //     return it.value();
    // }
    return "";
}
